﻿using TinyGet.Models;
using TinyGet.Helpers;
using System.Linq;
using System.Linq.Expressions;
using System;

public class TinyGetRepository
{
    TinyGetDataContext db = new TinyGetDataContext();

    public TinyGetRepository()
    {
    }

    public string getLink(string hash)
    {
        TinyLink link = db.TinyLinks.Where(p => p.Hash.Equals(hash.ToLower())).Single();
        link.Visits++;
        db.SubmitChanges();
        return link.Url;
    }

    public string addLink(string url)
    {

        if (url.IndexOf("://") == -1) url = "http://" + url;
    
        TinyLink link = new TinyLink();
        link.Url = url.ToLower();
        link.Hash = "";
        link.AbusiveFlag = false;
        link.AbusiveVotes = 0;
        link.Visits = 0;
        link.Votes = 0;
        link.Created = DateTime.Now;
        db.TinyLinks.InsertOnSubmit(link);
        db.SubmitChanges();

        string hash = Base36.Encode(link.ID).ToLower();
        link.Hash = hash;
        db.SubmitChanges();

        return hash;
    }
}